package com.pingan.hive.udf;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.hadoop.hive.ql.exec.UDF;

/*
 * 获得两个时间相差的天数，用于分母，故相差月数不能为0.<br>
 * 如为同日则相并为1
 */
public class DateDiff extends UDF {

	public String evaluate(String startDate, String endDate) throws Exception {

		if (startDate == null || endDate == null || "".equals(startDate)
				|| "".equals(endDate)) {
			return "1";
		}

		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date end = sd.parse(endDate);
		Date start = sd.parse(startDate);

		long diff = end.getTime() - start.getTime();

		if (diff <= 0) {
			return "1";
		} else {
			long days = diff / (1000 * 60 * 60 * 24);
			if (days == 0) {
				days = 1;
			}
			return Long.valueOf(days).toString();
		}
	}

	public static void main(String[] args) throws Exception {
		DateDiff g = new DateDiff();
		System.out.println(g.evaluate("2013-04-06 04:12:06",
				"2013-04-07 04:11:01"));
	}

}
